package com.javaweb.demo.servlet;

import com.javaweb.demo.dao.UserDaolmpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

/**
 * Servlet implementation class UpLoadServet
 */
public class UploadServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=UTF-8");
        boolean isMultipart=ServletFileUpload.isMultipartContent(request);
        System.out.println(isMultipart);
        if(isMultipart)
        {
            FileItemFactory factory=new DiskFileItemFactory();
            ServletFileUpload upload=new ServletFileUpload(factory);
            try {
                List<FileItem> items=upload.parseRequest(request);
                Iterator<FileItem> it = items.iterator();
                String username ="\0";
                while(it.hasNext())
                {
                    FileItem item = it.next();
                    if(item.isFormField()) {
                        username = item.getString("utf-8");
                        System.out.println(username);
                    }
                    else {
                        String filename=item.getName();
                        UserDaolmpl user = new UserDaolmpl();
                        if (!user.upload(item.getInputStream(),filename)) {
                            System.out.println("fail to upload file");
                        }
                        //File file=new File(path,filename);
                        //item.write(file);
                        if (username.equals("daikunqi")) {
                            request.getRequestDispatcher("successM.jsp").forward(request, response);
                        }
                        else {
                            request.getRequestDispatcher("success.jsp").forward(request, response);
                        }
                        return;
                    }

                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

